#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/1/17 16:21
# @Author  : wanghaoran
# @File    : similar_question_process.py
# from configs.mq_config import insert_url, delete_url, compare_url
import json
import requests
import mysql.connector
from mysql.connector import Error

insert_url = "http://113.31.111.86:19003/knowledge1/insert_data/"
delete_url = "http://113.31.111.86:19003/knowledge1/delete_data/"
compare_url = "http://113.31.111.86:19003/knowledge1/compare_sim_question/"
mapping_url = "http://113.31.111.86:19003/knowledge1/get_project_base/"

# 数据库配置
db_config = {
    "host": "113.31.111.86",
    "port": 19009,
    "user": "root",
    "password": "UnidteVdfZwfFERW8nZp5@20210628Hz",
    "database": "llm_data_milvus_final",
}

# 创建数据库连接
def db_connection():
    conn = None
    try:
        conn = mysql.connector.connect(**db_config)
    except Error as e:
        print(e)
    return conn

conn = db_connection()
cursor = conn.cursor()


def insert_sim_question(data):
    if "question" in data:
        if data["question"] and data["question"] == "":
            return {"code": 400, "message": "Parameter question should be string and the content should be not empty!", "data": None}
        question_list = [data["question"]]
    else:
        return {"code": 400, "message": "Parameter question should be given!", "data": None}
    if "question_id" in data:
        question_id_list = [data["question_id"]]
    else:
        return {"code": 400, "message": "Parameter question_id should be given!", "data": None}
    if "answer" in data:
        answer_list = [data["answer"]]
    else:
        return {"code": 400, "message": "Parameter answer should be given!", "data": None}
    if "question_extend" in data:
        question_extend_list = [data["question_extend"]]
    else:
        question_extend_list = [[]]
        
    if "thirdId" in data:
        thirdId = data["thirdId"]
    else:
        return {"code": 400, "message": "Parameter thirdId should be given!", "data": None}
    
    cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdId,))
    rows = cursor.fetchall()
    if rows:
        base_name = rows[0][3]
        thirdParentId = rows[0][6]
        cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
        rows = cursor.fetchall()
        if rows:
            thirdParentId = rows[0][6]
            cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
            rows = cursor.fetchall()
            if rows:
                project_name = rows[0][3]
            else:
                return {"code": 400, "message": "thirdId对应子表不存在上一层级", "data": None}
        else:
            return {"code": 400, "message": "thirdId对应子表不存在上一层级", "data": None}
    else:
        return {"code": 400, "message": "thirdId对应子表不存在", "data": None}

    insert_data = {
        "text": json.dumps(question_list),
        "text_uid": json.dumps(question_id_list),
        "detail_text": json.dumps(answer_list),
        "embedding": json.dumps(["m3e-base"]),
        "meta_data": json.dumps([{}]),
        "source": json.dumps(["sim_ques_ext"]),
        "project": json.dumps([project_name]),
        "base": json.dumps([base_name]),
        "base_type": json.dumps([""]),
        "sim_text": json.dumps(question_extend_list),
        "comment": "park_front"
    }
    try:
        res = requests.post(insert_url, data=insert_data)
        print(res.json())
    except Exception as e:
        print("error", e)
        return {"code": 400, "message": "insert fail!", "data": None}
    return {"code": 200, "message": "insert success!", "data": None}


def delete_sim_question(data):
    if "question_id" in data:
        question_id_list = [data["question_id"]]
    else:
        return {"code": 400, "message": "Parameter question_id should be given!", "data": None}

    delete_data = {
            "embedding": "m3e-base",
            "question_uid": json.dumps(question_id_list)
        }
    try:
        res = requests.post(delete_url, data=delete_data)
        print(res.json())
    except Exception as e:
        print("error", e)
        return {"code": 400, "message": "delete fail!", "data": None}
    return {"code": 200, "message": "delete success!", "data": None}


def update_sim_question(data):
    if "question" in data:
        if data["question"] and data["question"] == "":
            return {"code": 400, "message": "Parameter question should be string and the content should be not empty!",
                 "data": None}
        question = data["question"]
    else:
        return {"code": 400, "message": "Parameter question should be given!", "data": None}
    if "question_id" in data:
        question_id = data["question_id"]
    else:
        return {"code": 400, "message": "Parameter question_id should be given!", "data": None}
    if "answer" in data:
        answer = data["answer"]
    else:
        return {"code": 400, "message": "Parameter answer should be given!", "data": None}
    if "question_extend" in data:
        sim_text = data["question_extend"]
    else:
        sim_text = []
    
    if "thirdId" in data:
        thirdId = data["thirdId"]
    else:
        return {"code": 400, "message": "Parameter thirdId should be given!", "data": None}
    
    cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdId,))

    rows = cursor.fetchall()
    if rows:
        base_name = rows[0][3]
        thirdParentId = rows[0][6]
        cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
        rows = cursor.fetchall()
        if rows:
            thirdParentId = rows[0][6]
            cursor.execute("SELECT * FROM table_platform_kgbase WHERE thirdId = %s and status = 1", (thirdParentId,))
            rows = cursor.fetchall()
            if rows:
                project_name = rows[0][3]
            else:
                return {"code": 400, "message": "thirdId对应子表不存在上一层级", "data": None}
        else:
            return {"code": 400, "message": "thirdId对应子表不存在上一层级", "data": None}
    else:
        return {"code": 400, "message": "thirdId对应子表不存在", "data": None}
    
    try:
        compare_data = {
            "text": question,
            "text_uid": question_id,
            "detail_text": answer,
            "project": project_name,
            "base": base_name,
            "sim_text": json.dumps(sim_text)
        }
        compare_res = requests.post(compare_url, data=compare_data)
        if compare_res.status_code == 200:
            compare_res = compare_res.json()
            if "insert" in compare_res:
                is_insert = compare_res["insert"]
            else:
                is_insert = False
            # print("compare_res", compare_res)
            if compare_res["status"] == 200:
                update_question = compare_res["data"]["update_question"]
                add_sim_item = compare_res["data"]["add_sim_item"]
                delete_sim_item = compare_res["data"]["delete_sim_item"]
                if delete_sim_item or update_question == "true":
                    # 删除
                    del_uid_list = []
                    if update_question == "true":
                        del_uid_list.append(data["question_id"])
                    del_uid_list.extend([item["extend_id"] for item in delete_sim_item])
                    del_res = requests.post(delete_url, data={
                        "question_uid": json.dumps(del_uid_list),
                        "project": project_name,
                        "base": base_name,
                        "embedding": "m3e-base",
                        "is_association": "false",
                    })
                    print("del_res", del_res.json())
                if add_sim_item or is_insert:
                    # 插入
                    insert_data = {
                        "text": json.dumps([question]),
                        "text_uid": json.dumps([question_id]),
                        "detail_text": json.dumps([answer]),
                        "embedding": json.dumps(["m3e-base"]),
                        "meta_data": json.dumps([{}]),
                        "source": json.dumps(["sim_ques_ext"]),
                        "project": json.dumps([project_name]),
                        "base": json.dumps([base_name]),
                        "base_type": json.dumps([""]),
                        "sim_text": json.dumps([add_sim_item]),
                        "comment": "park_front"
                    }

                    insert_res = requests.post(insert_url, data=insert_data)
                    print("insert_res", insert_res.json())
            else:
                return {"code": 400, "message": "update fail!", "data": None}
        else:
            return {"code": 400, "message": "update fail!", "data": None}
    except Exception as e:
        print("error", e)
        return {"code": 400, "message": "update fail!", "data": None}
    return {"code": 200, "message": "update success!", "data": None}
